# Create your views here.
from django.http import HttpResponse
import json
import logging
from jboss_observer.analyzer.models import Jboss_Instance, Report,Meta_Report
from jboss_observer.analyzer.models import META_MAP
import traceback
import ast

logger = logging.getLogger(__name__)
jboss_instances = {} 

def load_main(request):
    
    try:
        data_map={}
        for i in jboss_instances.iterkeys():
            j_inst=Jboss_Instance.objects.get(id=jboss_instances[i].pk)
            reports=Report.objects.filter(jboss_instance=j_inst)
            
            if len(j_inst.meta_data) >8 :
                instance_meta=ast.literal_eval(j_inst.meta_data)
            else:
                instance_meta={}
            
            dataset={"1":{'label':"Code Cache","data":[]},"2":{'label':"Code Cache Max","data":[]},"3":{'label':"Eden Space","data":[]},"4":{'label':"Eden Space Max","data":[]},"5":{'label':"Survivor Space","data":[]},"6":{'label':"Survivor Space Max","data":[]},"7":{'label':"Old Gen Space","data":[]},"8":{'label':"Old Gen Space Max","data":[]},"9":{'label':"Perm Gen Space","data":[]},"10":{'label':"Perm Gen Space Max","data":[]}}
            
            for j in xrange(0,len(reports)):
                rep=reports[j]        
                dt=float(rep.report_date)*1000
                dataset["1"]["data"].append([dt,rep.mem_cur_1])
                dataset["2"]["data"].append([dt,rep.mem_max_1])
                dataset["3"]["data"].append([dt,rep.mem_cur_2])
                dataset["4"]["data"].append([dt,rep.mem_max_2])
                dataset["5"]["data"].append([dt,rep.mem_cur_3])
                dataset["6"]["data"].append([dt,rep.mem_max_3])
                dataset["7"]["data"].append([dt,rep.mem_cur_4])
                dataset["8"]["data"].append([dt,rep.mem_max_4])
                dataset["9"]["data"].append([dt,rep.mem_cur_5])
                dataset["10"]["data"].append([dt,rep.mem_max_5])
            
            
            meta_reports=Meta_Report.objects.filter(jboss_instance=j_inst)
            dataset2={"1":{'label':"Used Memory","data":[]},"2":{'label':"Total Memory","data":[]}}
            dataset3={"1":{'label':"CPU Times","data":[]},"2":{'label':"Thread","data":[]}}
            thread_list=""
            last_cpu_time=0
            for j in xrange(0,len(meta_reports)):
                metad=meta_reports[j]
                dt=float(metad.report_date)*1000
                meta=ast.literal_eval(metad.meta_data)
                total=float(meta[META_MAP['Total Memory']])
                free=float(meta[META_MAP['Free Memory']])
                used=total-free
                dataset2["1"]["data"].append([dt,used])
                dataset2["2"]["data"].append([dt,total])
                
                if j == 0 :
                    dataset3["1"]["data"].append([dt,0])
                else:
                    dataset3["1"]["data"].append([dt,(float(meta[META_MAP['Cpu Time']])/1000)-last_cpu_time])
                
                last_cpu_time=float(meta[META_MAP['Cpu Time']])/1000
                
                dataset3["2"]["data"].append([dt,meta[META_MAP['Threads']]])
                threads=metad.meta_data_thread
                if threads !=None and len(threads)>0:
                    thread_list=thread_list+"///"
                    thread_list=thread_list+threads
                else:
                    thread_list=thread_list+"EMPTY"
            
            data_map[jboss_instances[i].pk]={"dataset":dataset,"dataset2":dataset2,"dataset3":dataset3,"threads":thread_list,"instance":{"id":j_inst.pk,"name":j_inst.name,'meta':instance_meta}}
        
        result={}
        result["data"]=data_map
        result["settings"]={"1":["Code Cache"],"2":["Code Cache Max"],"3":["Eden Space"],"4":["Eden Space Max"],"5":["Survivor Space"],"6":["Survivor Space Max"],"7":["Old Gen Space"],"8":["Old Gen Space Max"],"9":["Perm Gen Space"],"10":["Perm Gen Space Max"]}         
    except Exception:
        logger.error("Error while preparing monitoring data."+traceback.format_exc())
    return HttpResponse(json.dumps(result))

def delete_reports(request):
    instanceId=request.POST.get('instanceId') 
    j_inst=Jboss_Instance.objects.get(id=instanceId)
    Report.objects.filter(jboss_instance=j_inst).delete()
    return HttpResponse(json.dumps("OK"))

def export_reports(request):
    import csv
    from datetime import datetime as dt
    # Create the HttpResponse object with the appropriate CSV header.
    instanceId=request.GET.get('instanceId') 
    j_inst=Jboss_Instance.objects.get(id=instanceId)
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename='+j_inst.name+'.csv'
    
    writer = csv.writer(response)
    
    writer.writerow(["Date","Code Cache","Code Cache Max","Eden Space","Eden Space Max","Survivor Space","Survivor Space Max","Old Gen Space","Old Gen Space Max","Perm Gen Space","Perm Gen Space Max"])
    reports=Report.objects.filter(jboss_instance=j_inst)
    for j in xrange(0,len(reports)):
            rep=reports[j]
            t = dt.fromtimestamp(float(rep.report_date))
            writer.writerow([t.strftime('%Y-%m-%d %H:%M:%S'),rep.mem_cur_1,rep.mem_max_1,rep.mem_cur_2,rep.mem_max_2,rep.mem_cur_3,rep.mem_max_3,rep.mem_cur_4,rep.mem_max_4,rep.mem_cur_5,rep.mem_max_5])

    return response
